package com.framework.controller.system;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.util.ByteSource;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.framework.annotation.SystemLog;
import com.framework.controller.index.BaseController;
import com.framework.entity.CurrentDBFormMap;
import com.framework.entity.DSAuthInfoFormMap;
import com.framework.entity.DSCorpAuthFormMap;
import com.framework.entity.DatacenterFormMap;
import com.framework.entity.DatasourceFormMap;
import com.framework.entity.DatasourceFuncFormMap;
import com.framework.entity.HewkeuserFormMap;
import com.framework.entity.ConsoleuserFormMap;
import com.framework.entity.ResFormMap;
import com.framework.entity.CompanyFormMap;
import com.framework.entity.ClientDatasourceFormMap;
import com.framework.entity.factory.FormmapFactory;
import com.framework.entity.view.DatasourceFuncViewFormMap;
import com.framework.plugin.PageView;
import com.framework.plugin.test.ContextHolder;
import com.framework.plugin.token.Token;
import com.framework.util.Common;
import com.framework.util.GetDataFromOtherDB;
import com.framework.util.PasswordHelper;
import com.framework.util.WXUtil;
import com.framework.util.datasource.EnvironmentFileInfo;
import com.framework.util.shell.CreateDBBuilder;
import net.sf.json.JSONObject;

@Controller
@RequestMapping("/dataclient/")
public class DataclientController extends BaseController {
	@SuppressWarnings("unused")
	private final static Logger logger = Logger.getLogger(DataclientController.class);

	List<ResFormMap> res = null;
	public static int max_db = Integer.parseInt(EnvironmentFileInfo.createdb.getProperty("max_db"));
	public static int idCode;

	// 获取界面UI
	@RequestMapping(value = "list")
	public String listUI(Model model) throws Exception {
		res = findByRes();
		model.addAttribute("res", getButtomM(res));
		return Common.BACKGROUND_PATH + "/system/dataclient/list";
	}

	/**
	 * 判断是不是企业用户test
	 * 
	 * @author 吴华杰
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "isEnUsertest")
	public String isEnUsertest(Model model) throws Exception {
		// TODO
		// String parentId = getPara("parentId");
		// String name = getPara("name");
		// 找到这个用户买了什么产品，不分开找，我一次性找
		DatacenterFormMap datacenterFormMap = getFormMap(DatacenterFormMap.class);
		Map<String, Object> map = DatacenterFormMap.mapper().findClientInfoViaId(datacenterFormMap);
		if (map == null) {
			return "failed";
		}

		String db_name = map.get("db_name").toString();
		if (map.get("parentId").toString().equals("0")) {
			// 说明是老爸，就不找了
		} else {
			// 说明不是老爸，继续找
			datacenterFormMap.clear();
			datacenterFormMap.put("db_name", db_name);
			datacenterFormMap.put("parentId", 0);
			map = DatacenterFormMap.mapper().findClientInfoViaId(datacenterFormMap);
		}

		if (map.get("st_id_user") == null) {
			return "failed";
		}
		// if (isLockStatus(map)) {
		// return "success";
		// }
		return "failed";
	}

	@ResponseBody
	@RequestMapping("findByPage")
	public PageView findByPage(String draw, String length, String start) throws Exception {
		DatasourceFuncViewFormMap formMap = new DatasourceFuncViewFormMap();
		formMap.put("$orderby", "order by ds_update_time desc");
		formMap.put("$search", getsearch());
		formMap.put("keyCloumn",  getKeyCloumn());
		formMap.put("name", "CRM");
		formMap = toFormMap(formMap, draw, length, start);
		pageView = formMap.findByPage_Names(pageView);
		return pageView;
	}

	@ResponseBody
	@RequestMapping("getButton")
	public String getButton() throws Exception {
		return getButtomB(res);
	}

	// 显示添加内容的页面
	@RequestMapping("addUI")
	@Token(save = true)
	public String addUI(Model model) throws Exception {
		return Common.BACKGROUND_PATH + "/system/dataclient/add";
	}

	@ResponseBody
	@RequestMapping("addEntity")
	@Token(remove = true)
	/**
	 * 1.初始化环境，属性大多数是从外部文件取得， 检测参数是否符合规格 2.开始创建数据库，如果设置模式为多线程模式，将会启动线程，去多创建一个线程
	 * 3.检测个人创建企业的数目，检测个人状态 4.保存数据
	 * 
	 * @author Lyon 创建时间：2016年11月5日 上午9:43:21
	 * @param model
	 * @param request
	 * @return "overtop" "failed" "swicth dataSource failed" "success"
	 *         "transfered datasource failed"
	 * @throws Exception
	 */
	public String addEntity(Model model, HttpServletRequest request) throws Exception {
		EnvironmentFileInfo environmentFileInfo = new EnvironmentFileInfo();
		environmentFileInfo.initProperties();

		Object[] ids = null;
		HashMap<String, Object[]> userHashmap = new HashMap<>();
		String dbusername = RandomStringUtils.randomAlphabetic(6);
		String dbpassword = RandomStringUtils.randomAlphabetic(6);

		DatacenterFormMap datacenterFormMap = getFormMap(DatacenterFormMap.class);
		if (!datacenterFormMap.containsKey("cellphone")) {
			HashMap<String, Object> hashMap = getMapFromRequest();
			datacenterFormMap = getMapformDataMap(DatacenterFormMap.class, hashMap);
		}
		// 得到相关属性
		String username = (String) datacenterFormMap.get("username");
		String password = (String) datacenterFormMap.get("password");
		String cellphone = datacenterFormMap.getStr("cellphone");
		String corp_id = "";

		boolean copr_id_flag = datacenterFormMap.containsKey("corp_id");
		if (copr_id_flag) {
			datacenterFormMap.put("username", cellphone);
			datacenterFormMap.put("password", "12345678");
			corp_id = datacenterFormMap.getStr("corp_id");
			username = cellphone;
		}

		boolean check_flag = checkRestrict(datacenterFormMap);
		if (!check_flag) {
			return "failed";
		}

		final String SMS_MODE = EnvironmentFileInfo.createdb.getProperty("SMS_MODE");
		final String dbPosition = EnvironmentFileInfo.jdbc.getProperty("dbPosition");
		final String enterprise = datacenterFormMap.get("enterprise").toString();

		CurrentDBFormMap currentDBFormMap = FormmapFactory.getBeanFormMap(CurrentDBFormMap.class);
		currentDBFormMap = currentDBFormMap.findbyFrist();
		int currentDB = Integer.parseInt(currentDBFormMap.getStr("currentDB"));
		//
		final String db_name = EnvironmentFileInfo.createdb.getProperty("dbHead") + currentDB;
		final String db_nameNext = EnvironmentFileInfo.createdb.getProperty("dbHead") + (currentDB + 1);

		DatasourceFormMap datasourceFormMap = getFormMap(DatasourceFormMap.class);
		datasourceFormMap.put("db_position", dbPosition);
		datasourceFormMap.put("db_name", db_name);
		datasourceFormMap.put("db_username", dbusername);
		datasourceFormMap.put("db_password", dbpassword);
		datasourceFormMap.put("enterprise", enterprise);
		if (copr_id_flag) {
			datasourceFormMap.put("corp_id", corp_id);
			datasourceFormMap.put("manager", cellphone);
		}

		// 查询用户数据库的tc_user 表的情况 ,实际上电话号码与，什么对不上，所以查询结果为null，接下来就是查不出东西
		DatasourceFormMap user = DatasourceFormMap.mapper().findDBTablesViews(db_name);
		// TODO: handle exception
		CreateDBBuilder createDBBuilder=new CreateDBBuilder();
		createDBBuilder.createMultiDB(db_name, dbusername, dbpassword, db_nameNext);
		
		// 要在客户的数据库创建他，还有相关的权限
		// 配置相应的套餐
		// db_position,以后不能写死
		datasourceFormMap.put("db_position", dbPosition);// 将来的位置
		datasourceFormMap.put("owner", cellphone);
		datasourceFormMap.put("manager", username);

		// 检测手机是不是存在了套餐
		String check_cellphone = datacenterFormMap.getStr("cellphone");

		int code_en_max = checkClientPackage(check_cellphone);
		int code_en_user = 0;
		if (code_en_max == 0) {
			code_en_user = checkUser(datacenterFormMap);
		}
		if (code_en_max == 0) {
			userHashmap = saveDatauser(datacenterFormMap, db_name, userHashmap);
			ids = userHashmap.get("ids");
		} else if (code_en_max == 1 || code_en_user == 1) {
			userHashmap = updateDatauser(datacenterFormMap, db_name, userHashmap);
			datacenterFormMap.clear();
			datacenterFormMap.put("cellphone", cellphone);
			datacenterFormMap = datacenterFormMap.findbyFrist();

			ids = userHashmap.get("ids");
			Object[] salts = userHashmap.get("salts");
			Object[] passwords = userHashmap.get("passwords");

			ids[2] = datacenterFormMap.get("id");
			salts[2] = datacenterFormMap.get("credentialsSalt");
			passwords[2] = datacenterFormMap.get("password");
		} else if (code_en_max == 2) {
			return "overtop";
		}

		saveMatchPackage(datacenterFormMap, userHashmap, datasourceFormMap);

		HashMap<String, Object> hashMap_wx = new HashMap<>();
		if (copr_id_flag) {
			hashMap_wx = saveWXinfo(datacenterFormMap);
			if (hashMap_wx == null) {
				return "save wx_info is failed";
			}
		}

		if (!GetDataFromOtherDB.getDataFromCellphoneAdd(cellphone, db_name, request)) {// 以后分布式
			datacenterFormMap = FormmapFactory.getBeanFormMap(DatacenterFormMap.class);
			datacenterFormMap.deleteById(ids[0].toString());
			datacenterFormMap.deleteById(ids[1].toString());
			datasourceFormMap.deleteById(datasourceFormMap.getStr("id"));
			;
			logger.error("swicth dataSource failed");
			return "swicth dataSource failed";
		}

		if (ContextHolder.getCustomerType().equals("dataSource")) {
			datasourceFormMap.deleteByNames();
			logger.error("swicth dataSource failed");
			return "swicth dataSource failed";
		}

		try {
			// 保存公司信息
			saveCompanyInfo(datasourceFormMap);
			saveHewkeUser(userHashmap, cellphone, password, db_name, username);
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			try {
				for (int i = 3; i > 0; i--) {
					new HewkeuserFormMap().deleteById(i + "");
				}
			} catch (Exception e2) {
				
			}

			ContextHolder.setCustomerType(ContextHolder.DATA_SOURCE_A);
			new DatasourceFormMap().deleteById(datasourceFormMap.getStr("id"));

			delDatauser(ids, code_en_max);
			return "transfered datasource failed";
		}

		// 清除session里面的失效数据

		HttpSession httpSession = request.getSession();
		httpSession.removeAttribute(request.getRequestedSessionId());
		ContextHolder.setCustomerType(ContextHolder.DATA_SOURCE_A);

		datacenterFormMap = FormmapFactory.getBeanFormMap(DatacenterFormMap.class);
		for (Object id : ids) {
			datacenterFormMap.put("id", id);
			datacenterFormMap.put("status", 1);
			datacenterFormMap.update();
		}
		if (copr_id_flag) {
			DSAuthInfoFormMap dsAuthInfoFormMap = FormmapFactory.getBeanFormMap(DSAuthInfoFormMap.class);
			DSCorpAuthFormMap dsCorpAuthFormMap = FormmapFactory.getBeanFormMap(DSCorpAuthFormMap.class);

			@SuppressWarnings("unchecked")
			List<Object> ai_id_list = (List<Object>) hashMap_wx.get("ai_id_list");
			Object ca_id = hashMap_wx.get("ca_id");
			Object ds_id = datasourceFormMap.get("id");

			for (Object ai_id : ai_id_list) {
				dsAuthInfoFormMap.put("ds_id", ds_id);
				dsAuthInfoFormMap.put("ai_id", ai_id);
				dsAuthInfoFormMap.replace();
			}

			dsCorpAuthFormMap.put("ds_id", ds_id);
			dsCorpAuthFormMap.put("ca_id", ca_id);
			dsCorpAuthFormMap.replace();
		}

		currentDBFormMap.put("currentDB", currentDB + 1);
		datasourceFormMap.put("status", 1);
		datasourceFormMap.update();
		currentDBFormMap.update();

		// if (SMS_MODE.equals("1")) {
		// CCPRestSDK.
		// }

		return "success";
	}

	/**
	 * 保存wx端发来的消息
	 * 
	 * @author Lyon 创建时间：2016年11月8日 下午4:54:40
	 * @param datasourceFormMap
	 * @param datacenterFormMap
	 * @return
	 * @throws Exception
	 */
	private HashMap<String, Object> saveWXinfo(DatacenterFormMap datacenterFormMap) throws Exception {
		DatasourceFormMap datasourceFormMap = getMapformDataMap(DatasourceFormMap.class, getMapFromRequest());
		Object wx_return_info = datasourceFormMap.get("wx_return_info");
		JSONObject parajson = JSONObject.fromObject(wx_return_info);
		String suite_id = datasourceFormMap.getStr("suite_id");
		HashMap<String, Object> hashMap = new HashMap<>();
		boolean flag = WXUtil.saveAuthCropInfo(parajson, suite_id, hashMap);
		if (flag == false) {
			return null;
		}

		return hashMap;
	}

	

	/**
	 * 完善，删除datauserformmap，当用户只有一个绑定时，全部删除，当用户，有多个绑定时，至删除，内部帐号
	 * 
	 * @author 李品良 创建时间：2016年10月7日 上午10:14:21
	 * @param ids
	 * @param code
	 * @throws Exception
	 */
	private void delDatauser(Object[] ids, int code) throws Exception {
		// TODO Auto-generated method stub
		if (code == 0) {
			for (int i = 0; i < ids.length; i++) {
				new DatacenterFormMap().deleteById(ids[i].toString());
			}
		} else {
			for (int i = 0; i < ids.length - 1; i++) {
				new DatacenterFormMap().deleteById(ids[i].toString());
			}
		}
	}


	private void saveCompanyInfo(DatasourceFormMap datasourceFormMap) throws Exception {
		CompanyFormMap companyFormMap = FormmapFactory.getBeanFormMap(CompanyFormMap.class);
		companyFormMap.put("id", 1);
		String companyName = datasourceFormMap.getStr("enterprise");
		companyFormMap.put("companyName", companyName);
		companyFormMap.put("companyPrincipal", datasourceFormMap.get("manager"));
		companyFormMap.put("companyCode", datasourceFormMap.get("companyCode"));
		companyFormMap.update();
	}

	/**
	 * 检测是否存在该用户，
	 * 
	 * @author Lyon 创建时间：2016年11月5日 上午10:00:32
	 * @param datacenterFormMap
	 * @return 1（标识存在） 0（表示不存在）
	 */
	private int checkUser(DatacenterFormMap datacenterFormMap) {
		String cellphone = datacenterFormMap.getStr("cellphone");
		List<DatacenterFormMap> list = datacenterFormMap.findByAttribute("cellphone", cellphone);

		if (list.size() > 0) {
			return 1;
		}

		return 0;
	}


	

	private boolean checkRestrict(DatacenterFormMap datacenterFormMap) {
		String cellphone = datacenterFormMap.get("cellphone").toString();
		String username = datacenterFormMap.get("username").toString();
		String password = datacenterFormMap.get("password").toString();

		if (!Common.isCellphone(cellphone)) {
			return false;
		}

		if (Common.isEmpty(username)) {
			return false;
		} else if (username.length() < 5 && username.length() > 20) {
			return false;
		}

		if (Common.isEmpty(password)) {
			return false;
		} else if (password.length() < 5 && password.length() > 20) {
			return false;
		}
		return true;
	}

	/**
	 * 检测用户买的企业数是否大于最大值，：由于用户存在免费开户的现象，所以每个人都有
	 * 
	 * @author 李品良 创建时间：2016年8月26日 下午8:40:05
	 * @param check_cellphone
	 * @param hashMap
	 * @return overflow:0:表示客户没有购买套餐; 1:表示，用户购买了套餐，并且正常 ；2:表示，企业数超出套餐上限
	 */
	private int checkClientPackage(String check_cellphone) {
		DatasourceFormMap datasourceFormMap = new DatasourceFormMap();
		datasourceFormMap.put("owner", check_cellphone);
		datasourceFormMap.put("status", 1);
		List<DatasourceFormMap> list_all = datasourceFormMap.findByNames_Page();
		if (list_all.size() > 0) {
			int current = list_all.size();
			// int max=list_all.get(0).getInt("max");

			if (current == 0) {
				return 0;
			}
			int overflow = max_db - (current + 1) > -1 ? 1 : 2;
			idCode = list_all.get(0).getInt("id");
			return overflow;
		}
		return 0;
	}

	private void saveHewkeUser(HashMap<String, Object[]> hashMap, String cellphone, String password, String db_name,
			String username) throws Exception {
		Double doubleCellphone = new Double(cellphone);
		Double doubleNumbers = new Double("10000000000");
		saveHewke(username, password, doubleCellphone, "3", hashMap.get("passwords")[0], hashMap.get("salts")[0]);
		saveHewke("admin_" + db_name, password, doubleNumbers + doubleCellphone, "2", hashMap.get("passwords")[1],
				hashMap.get("salts")[1]);
		saveHewke("ROOT_" + db_name, password, 2 * doubleNumbers + doubleCellphone, "1", hashMap.get("passwords")[2],
				hashMap.get("salts")[2]);

	}

	/**
	 * 保存用户数据源信息关系
	 * 
	 * @author 李品良
	 * @param datacenterFormMap
	 * @param datasourceFormMap
	 * @param hashMap
	 * @throws Exception
	 */
	private void saveUserDatasource(DatacenterFormMap datacenterFormMap, DatasourceFormMap datasourceFormMap,
			HashMap<String, Object[]> hashMap) throws Exception {
		for (int i = 0; i < hashMap.get("ids").length; i++) {
			ClientDatasourceFormMap ClientDatasourceFormMap = new ClientDatasourceFormMap();
			ClientDatasourceFormMap.put("client_id", hashMap.get("ids")[i]);
			ClientDatasourceFormMap.put("datasource_id", datasourceFormMap.get("id"));
			ClientDatasourceFormMap.put("status", 1);
			ClientDatasourceFormMap.save();
		}
	}

	private void saveDatasource(DatasourceFormMap datasourceFormMap) {
		try {
			datasourceFormMap.put("companyCode", RandomStringUtils.randomNumeric(6));
			datasourceFormMap.put("weixinid", 1);
			datasourceFormMap.put("weixinparentid", 0);
			datasourceFormMap = datasourceFormMap.save();
		} catch (DuplicateKeyException e) {
			saveDatasource(datasourceFormMap);
		} catch (Exception e) {
			try {
				datasourceFormMap.deleteById(datasourceFormMap.get("id").toString());
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
	}

	/**
	 * 这里要保存三个管理员的相关连接池，以及管理的相关套餐
	 * 
	 * @author 李品良
	 * @param datacenterFormMap
	 * @param matchPackage
	 * @param hashMap
	 * @param datasourceFormMap
	 * @throws Exception
	 */
	private void saveMatchPackage(DatacenterFormMap datacenterFormMap, HashMap<String, Object[]> hashMap,
			DatasourceFormMap datasourceFormMap) throws Exception {
		saveDatasource(datasourceFormMap);// 保存数据源
		saveUserDatasource(datacenterFormMap, datasourceFormMap, hashMap);// 保存数据源关系
		saveDatasourceFunc(datasourceFormMap);// 保存企业套餐关系

	}

	private void saveDatasourceFunc(DatasourceFormMap datasourceFormMap) throws Exception {
		// 如果管理员没登陆，那么就没有，
		DatasourceFuncFormMap datasourceFuncFormMap = FormmapFactory.getBeanFormMap(DatasourceFuncFormMap.class);
		Object crmPrice = null;
		Object entityPrice = null;
		Object spacePrice = null;

		DatafunctionFormMap datafunctionFormMap = FormmapFactory.getBeanFormMap(DatafunctionFormMap.class);
		datafunctionFormMap.put("where", "id in(11, 21, 31) order by id");
		List<DatafunctionFormMap> list = datafunctionFormMap.findByWhere();
		crmPrice = list.get(0).get("price");
		entityPrice = list.get(1).get("price");
		spacePrice = list.get(2).get("price");

		if (Common.findUserSession() != null) {
			ConsoleuserFormMap consoleuserFormMap = (ConsoleuserFormMap) Common.findUserSession();
			String accountName = consoleuserFormMap.getStr("accountName");
			datasourceFuncFormMap.put("df_creater", accountName);
			datasourceFuncFormMap.put("df_updater", accountName);

		}
		UUID uuid = UUID.randomUUID();
		datasourceFuncFormMap.put("info_code", Math.abs(uuid.getMostSignificantBits()));

		String expire_time = Common.addDateDay(15);
		datasourceFuncFormMap.put("expire_time", expire_time);
		datasourceFuncFormMap.put("datasource_id", datasourceFormMap.get("id"));
		datasourceFuncFormMap.put("func_parent_id", 10);
		datasourceFuncFormMap.put("func_id", 11);
		datasourceFuncFormMap.put("real_pay", crmPrice);
		datasourceFuncFormMap.save();

		datasourceFuncFormMap = FormmapFactory.getBeanFormMap(DatasourceFuncFormMap.class);
		datasourceFuncFormMap.put("datasource_id", datasourceFormMap.get("id"));
		datasourceFuncFormMap.put("func_parent_id", 20);
		datasourceFuncFormMap.put("func_id", 21);
		datasourceFuncFormMap.put("real_pay", entityPrice);
		datasourceFuncFormMap.save();

		datasourceFuncFormMap.clear();
		datasourceFuncFormMap.put("datasource_id", datasourceFormMap.get("id"));
		datasourceFuncFormMap.put("func_parent_id", 30);
		datasourceFuncFormMap.put("func_id", 31);
		datasourceFuncFormMap.put("real_pay", spacePrice);
		datasourceFuncFormMap.save();
	}

	/**
	 * 在tc_datacenter中保存，三个用户
	 * 
	 * @author 李品良
	 * @param datacenterFormMap
	 * @param db_name
	 * @return
	 * @throws Exception
	 */
	private HashMap<String, Object[]> saveDatauser(DatacenterFormMap datacenterFormMap, String db_name,
			HashMap<String, Object[]> hashMap) throws Exception {
		Object[] ids = new Object[3];
		Object[] salts = new Object[3];
		Object[] passwords = new Object[3];

		PasswordHelper passwordHelper = new PasswordHelper();
		String saltstr = passwordHelper.getSalt();
		String newPassword = passwordHelper.encryptPassword(datacenterFormMap.get("cellphone").toString(),
				datacenterFormMap.get("password").toString(), saltstr);
		salts[0] = saltstr;
		passwords[0] = newPassword;
		datacenterFormMap.put("credentialsSalt", saltstr);
		datacenterFormMap.put("password", newPassword);
		datacenterFormMap.put("parentId", 0);
		String username = datacenterFormMap.get("cellphone").toString();

		datacenterFormMap.replace();

		ids[0] = datacenterFormMap.get("id");

		String cellphone = datacenterFormMap.get("cellphone").toString();
		Double cellphoneDouble = new Double(cellphone);
		Double numberDouble = new Double("10000000000");
		datacenterFormMap.put("username", "admin_" + db_name);
		datacenterFormMap.put("password", "12345678");
		datacenterFormMap.remove("id");
		datacenterFormMap.put("level", "0");
		cellphoneDouble = cellphoneDouble + numberDouble;

		DecimalFormat format = new DecimalFormat("#");
		String sMoney = format.format(cellphoneDouble);
		datacenterFormMap.put("cellphone", sMoney);

		saltstr = passwordHelper.getSalt();
		newPassword = passwordHelper.encryptPassword(datacenterFormMap.get("cellphone").toString(),
				datacenterFormMap.get("password").toString(), saltstr);
		salts[1] = saltstr;
		passwords[1] = newPassword;
		datacenterFormMap.put("credentialsSalt", saltstr);
		datacenterFormMap.put("password", newPassword);

		username = datacenterFormMap.get("cellphone").toString();
		datacenterFormMap.replace();
		ids[1] = datacenterFormMap.get("id");

		cellphone = 2 + datacenterFormMap.get("cellphone").toString();
		datacenterFormMap.put("username", "ROOT_" + db_name);
		datacenterFormMap.put("password", "12345678");
		datacenterFormMap.remove("id");
		cellphoneDouble = cellphoneDouble + numberDouble;
		format = new DecimalFormat("#");
		sMoney = format.format(cellphoneDouble);
		datacenterFormMap.put("cellphone", sMoney);

		saltstr = passwordHelper.getSalt();
		newPassword = passwordHelper.encryptPassword(datacenterFormMap.get("cellphone").toString(),
				datacenterFormMap.get("password").toString(), saltstr);
		salts[2] = saltstr;
		passwords[2] = newPassword;
		datacenterFormMap.put("credentialsSalt", saltstr);
		datacenterFormMap.put("password", newPassword);

		username = datacenterFormMap.get("cellphone").toString();

		datacenterFormMap.replace();
		ids[2] = datacenterFormMap.get("id");

		hashMap.put("ids", ids);
		hashMap.put("salts", salts);
		hashMap.put("passwords", passwords);
		return hashMap;
	}

	/**
	 * 在tc_datacenter中保存，三个用户
	 * 
	 * @author 李品良
	 * @param datacenterFormMap
	 * @param db_name
	 * @param hashMap2
	 * @return
	 * @throws Exception
	 */
	private HashMap<String, Object[]> updateDatauser(DatacenterFormMap datacenterFormMap, String db_name,
			HashMap<String, Object[]> hashMap) throws Exception {
		Object[] ids = new Object[3];
		Object[] salts = new Object[3];
		Object[] passwords = new Object[3];

		PasswordHelper passwordHelper = new PasswordHelper();

		// //更新密码
		// List<DatacenterFormMap>
		// list=datacenterFormMap.findByAttribute("cellphone",
		// datacenterFormMap.get("cellphone"));
		// DatacenterFormMap datauserFormMapExtra=list.get(0);
		// String newPasswordExtra =
		// passwordHelper.encryptPassword(datauserFormMapExtra.get("cellphone").toString(),
		// datacenterFormMap.get("password").toString(), saltstrExtra);
		//
		// datauserFormMapExtra.put("credentialsSalt", saltstrExtra);
		// datauserFormMapExtra.put("password", newPasswordExtra);
		// datauserFormMapExtra.update();

		ids[0] = datacenterFormMap.get("id");
		Double numberDouble = new Double("10000000000");

		numberDouble = Math.random() * numberDouble + numberDouble;
		String cellphone = datacenterFormMap.get("cellphone").toString();
		Double cellphoneDouble = new Double(cellphone);
		datacenterFormMap.put("username", "admin_" + db_name);
		datacenterFormMap.put("password", "123456");
		datacenterFormMap.remove("id");
		datacenterFormMap.put("level", "0");
		cellphoneDouble = numberDouble;

		DecimalFormat format = new DecimalFormat("#");
		String sMoney = format.format(cellphoneDouble);
		datacenterFormMap.put("cellphone", sMoney);

		String saltstr = passwordHelper.getSalt();
		String newPassword = passwordHelper.encryptPassword(datacenterFormMap.get("cellphone").toString(),
				datacenterFormMap.get("password").toString(), saltstr);
		salts[0] = saltstr;
		passwords[0] = newPassword;
		datacenterFormMap.put("credentialsSalt", saltstr);
		datacenterFormMap.put("password", newPassword);
		datacenterFormMap.put("parentId", 0);

		String username = datacenterFormMap.get("cellphone").toString();
		ByteSource byteSource = ByteSource.Util.bytes(username + saltstr);
		System.out.println(byteSource);
		datacenterFormMap.save();
		ids[0] = datacenterFormMap.get("id");

		cellphone = 2 + datacenterFormMap.get("cellphone").toString();
		datacenterFormMap.put("username", "ROOT_" + db_name);
		datacenterFormMap.put("password", "123456");
		datacenterFormMap.remove("id");
		numberDouble = Math.random() * numberDouble + numberDouble;
		cellphoneDouble = numberDouble;
		format = new DecimalFormat("#");
		sMoney = format.format(cellphoneDouble);
		datacenterFormMap.put("cellphone", sMoney);

		saltstr = passwordHelper.getSalt();
		newPassword = passwordHelper.encryptPassword(datacenterFormMap.get("cellphone").toString(),
				datacenterFormMap.get("password").toString(), saltstr);
		salts[1] = saltstr;
		passwords[1] = newPassword;
		datacenterFormMap.put("credentialsSalt", saltstr);
		datacenterFormMap.put("password", newPassword);
		datacenterFormMap.put("parentId", 0);

		username = datacenterFormMap.get("cellphone").toString();
		byteSource = ByteSource.Util.bytes(username + saltstr);
		System.out.println(byteSource);

		datacenterFormMap = datacenterFormMap.save();
		ids[1] = datacenterFormMap.get("id");

		hashMap.put("ids", ids);
		hashMap.put("salts", salts);
		hashMap.put("passwords", passwords);
		return hashMap;
	}

	private void saveHewke(String username, String password, double tel, String id, Object newpassword, Object salt)
			throws Exception {
		HewkeuserFormMap hewkeuserFormMap = getFormMap(HewkeuserFormMap.class);
		hewkeuserFormMap.put("userName", username);

		DecimalFormat format = new DecimalFormat("#");
		String sMoney = format.format(tel);

		hewkeuserFormMap.put("accountName", sMoney);
		hewkeuserFormMap.put("tel", sMoney);
		hewkeuserFormMap.put("visible", 3);
		hewkeuserFormMap.put("parentId", "0");
		hewkeuserFormMap.put("id", id);

		if (id.equals("3")) {
			hewkeuserFormMap.put("directlyDepart", 1);
		} else {
			hewkeuserFormMap.put("directlyDepart", 0);
		}

		hewkeuserFormMap.put("addid", 0);

		hewkeuserFormMap.put("password", newpassword);
		hewkeuserFormMap.put("credentialsSalt", salt);

		hewkeuserFormMap.replace();
	}

	// 删除活动数据
	@ResponseBody
	@RequestMapping("deleteEntity")
	@SystemLog(module = "系统基础管理", methods = "数据中心-删除用户") // 凡需要处理业务逻辑的.都需要记录操作日志
	@Transactional(readOnly = false) // 需要事务操作必须加入此注解
	public String deleteEntity() throws Exception {
		DatacenterFormMap datacenterFormMap = new DatacenterFormMap();
		String[] ids = getParaValues("ids");
		if (ids.length > 0) {
			for (int i = 0; i < ids.length; i++) {
				datacenterFormMap.deleteById(ids[i]);
				// ActdropdownFormMap downFormMap = new ActdropdownFormMap();
				// downFormMap.put("cityid", ids[i]);
				// // 删除活动的同时去删除对应下拉框的数据
				// downFormMap.deleteByNames();
			}
		}
		return "success";
	}

	// 显示修改活动页面
	@RequestMapping("editUI")
	@Token(save = true)
	public String editUI(Model model) {
		String id = getPara("id");
		if (Common.isNotEmpty(id)) {
			model.addAttribute("datasourceFormMap", new DatasourceFormMap().findById(id));
		}
		return Common.BACKGROUND_PATH + "/system/dataclient/edit";
	}

	// 修改活动
	@ResponseBody
	@RequestMapping("editEntity")
	@Token(remove = true)
	@SystemLog(module = "系统基础管理", methods = "数据中心-修改用户") // 凡需要处理业务逻辑的.都需要记录操作日志
	@Transactional(readOnly = false) // 需要事务操作必须加入此注解
	public String editEntity(Model model) throws Exception {
		DatasourceFormMap datasourceFormMap = getFormMap(DatasourceFormMap.class);
		if (Common.isNotEmpty(datasourceFormMap.get("id").toString())) {
			datasourceFormMap.update();
		}
		return "success";
	}

	/////////// ----------- 只管上面这个 这里就得到数据了 ----------///////////////

	// 验证方法
	@ResponseBody
	@RequestMapping("isExist")
	public boolean isExist(String name) {
		DatacenterFormMap datacenterFormMap = getFormMap(DatacenterFormMap.class);
		List<DatacenterFormMap> list = datacenterFormMap.findByNames();
		if (list.size() == 0) {
			return true;
		} else {
			return false;
		}
	}

	// 修改时的验证方法
	@ResponseBody
	@RequestMapping("editisExist")
	public boolean editisExist() {
		DatacenterFormMap datacenterFormMap = getFormMap(DatacenterFormMap.class);
		// 先根据名称去找，没有就返回true
		// 有的话就判断是不是这id的记录，如果是的话也返回true
		// 否则返回false
		List<DatacenterFormMap> list = datacenterFormMap.findByAttribute("name", datacenterFormMap.get("name"));
		if (list.size() == 0) {
			return true;
		} else {
			if (list.size() >= 0) {
				List<DatacenterFormMap> list2 = datacenterFormMap.findByNames();
				if (list2.size() > 0) {
					return true;
				} else {
					return false;
				}
			}
			return false;
		}
	}

	// 修改时的验证方法
	@ResponseBody
	@RequestMapping("competenceisExist")
	public boolean competenceisExist() {
		DatacenterFormMap datacenterFormMap = getFormMap(DatacenterFormMap.class);
		// 先根据名称去找，没有就返回true
		// 有的话就判断是不是这id的记录，如果是的话也返回true
		// 否则返回false
		List<DatacenterFormMap> list = datacenterFormMap.findByAttribute("name", datacenterFormMap.get("name"));
		if (list.size() == 0) {
			return true;
		} else {
			if (list.size() >= 0) {
				List<DatacenterFormMap> list2 = datacenterFormMap.findByNames();
				if (list2.size() > 0) {
					return true;
				} else {
					return false;
				}
			}
			return false;
		}
	}

}
